package com.xyazm.order.mq.consumer;

import com.xyazm.common.constants.CoreConstant;
import com.xyazm.common.utils.MdcUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.core.RocketMQListener;

import java.nio.charset.StandardCharsets;

/**
 * 抽象的消费者MessageListener组件
 * @author xuyou
 * @date 2023年02月08日 22:10
 */
@Slf4j
public abstract class AbstractRocketMqListener implements RocketMQListener<MessageExt> {

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            String traceId = messageExt.getProperty(CoreConstant.TRACE_ID);
            if (StringUtils.isNotEmpty(traceId)) {
                MdcUtil.setTraceId(traceId);
            }
            String message = new String(messageExt.getBody(), StandardCharsets.UTF_8);
            log.info("AbstractRocketMqListener message:{}",message);
            onMessage(message);
        } finally {
            MdcUtil.removeTraceId();
        }
    }

    public abstract void onMessage(String message);
}
